﻿using OpenCvSharp.XImgProc;
using OpenCvSharp;
using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections;
using System.Collections.Concurrent;
using Newtonsoft.Json.Linq;

namespace SUNRPA.CONTROLS.IMPL.controls {
    /// <summary>
    /// TODO: 1、等待下载完成超时
    /// </summary>
    public class DownLoadFileNAction : BaseControlActions {
        public static LogUtil logger = new LogUtil(typeof(DownLoadFileNAction));
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            DownLoadFileNParam? param = item.ControlParam as DownLoadFileNParam;
            int downloadMethod = param.DownloadMethod;
            string webObject = param.WebObj;
            WebPage webPage = this.GetObjVar<WebPage>(ref webObject, globleData);
            if(webPage == null){ 
                throw new RpaRuntimeException("网页为空，无法进行下载操作");
            }
            string saveParentPath = param.SavePath;
            this.GetStringVar(ref saveParentPath, globleData);
            
            bool renameDownloadFile = param.RenameDownloadFile;
            string customName = param.SaveFileName;
            if(!renameDownloadFile){ 
                customName = "";
            }
            this.GetStringVar(ref customName, globleData);

            string savePathOutVarName = param.FileSavePathOutVar;
            this.GetStringVar(ref savePathOutVarName, globleData);

            string waitDialogTime = param.WaitDialogTime;
            this.GetStringVar(ref waitDialogTime, globleData);
            int wdt = int.Parse(waitDialogTime);
            
            bool waitDownloadFinish = param.WaitingDownloadFinish;
            string downloadExpireTimeString = param.ExpireTime;
            this.GetStringVar(ref downloadExpireTimeString, globleData);
            int downloadExpireTime = int.Parse(downloadExpireTimeString);

            NamePipeRequest request = new NamePipeRequest();
            if(downloadMethod == 0) {
                //通过点击按钮
                WebElement ele = param.WebEle as WebElement;
                //判断是否为web元素
                if(ele == null){ 
                    throw new RpaRuntimeException("元素不是web元素，无法点击下载操作");
                }
                request.method = DefaultContents.CLICK_ELE;
                request.requestData = new Dictionary<string, object>() { { "tabId", webPage.TabId}, { "ele", ele }, { "clickType", 0 }, { "buttonType", 0 } };

            } else { 
                //通过指定网址下载
                string downloadAddr = param.DownloadAddr;
                this.GetStringVar(ref downloadAddr, globleData);
                request.method = DefaultContents.DOWNLOAD_BYURL;
                request.requestData = new Dictionary<string, object>() { { "url", downloadAddr} };
            }
            BrowserUtil browserUtil;
            switch(webPage.Bt){ 
                case BrowserType.GOOGLE:
                    browserUtil = new ChromeUtil();
                    BridgeResponse resp = NamedPipeClientUtil.SendRequestV1(request);
                    if(!resp.code.Equals(CommunicationCode.OK)) {
                        throw new RpaRuntimeException($"下载文件出错:{resp.msg}");
                    }

                    //点击下载按钮或者通过网址下载后，处理下载对话框
                    try { 
                        browserUtil.DealDownLoadDialog(true, saveParentPath, customName, wdt);
                    }catch(RpaRuntimeException e){ 
                        logger.Info("没有找到对话框跳过该步骤");
                    }
                    JObject downloadItem = (JObject)browserUtil.SearchLatestDownloadTask();
                    //网址下载插件请求直接返回downloadid可以用来查下载进度，后期通过此id完善下载超时功能
                    //若是点击下载按钮需要用search方法查询到对应下载id（此功能后期再添加）
                    int downloadId = (int)downloadItem["id"];

                    //下载超时判断
                    if(waitDownloadFinish) { 
                        bool isExpire = browserUtil.IsDownloadExpire(downloadId, downloadExpireTime);
                        if(isExpire) { 
                            throw new RpaRuntimeException("下载超时");
                        }
                    }
                    string downLoadFilePath = downloadItem["filename"].ToString();
                    if(downLoadFilePath == null) {
                        throw new RpaRuntimeException("下载出错，返回下载路径为空");
                    }
                    this.saveVar(globleData, savePathOutVarName, new StringModel(savePathOutVarName, downLoadFilePath), DefaultContents.RUNNING_PARAM);
                    break;
                case BrowserType.IE:
                    break;
                case BrowserType.EDGE:
                    break;
                default:
                    throw new RpaRuntimeException("浏览器类型错误");
            }
            return currentIndex;
        }
    }
}
